var express = require('express');
var router = express.Router();

const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })
const fs = require('fs')
const path = require('path')

/* GET home page. */
router.post('/img', upload.single('good'), function(req, res) {
    //使用multer中间件处理二进制的文件流
    //使用fs模块把数据流写到硬盘上
    //返回图片的访问地址给前端
    console.log('file', req.file)
    const file = req.file
    //创建的读取流
    // __dirname
    console.log(file)
    const readStream = fs.createReadStream(path.resolve(`../node-restful/${file.path}`))
    const img = `${Date.now()}_${file.originalname}`
    //创建写入流
    const writeStream = fs.createWriteStream(path.resolve(`../node-restful/public/${img}`))
    //异步操作
    readStream.pipe(writeStream)
    writeStream.on('close', ()=>{
        res.json({err:0, msg:'success', data:{url: img}})
    })
   
});

module.exports = router;
